package com.tangweiliang.springboot;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.jws.WebService;
import java.util.Map;

/**
 * @author :tangweiliang
 * @date : 2022/12/30 15:54
 * 未来的你会感谢现在努力的自己
 */
public class TangweiliangSpringApplication {
    public static void run(Class clazz){
        // Spring容器
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(clazz);
        applicationContext.refresh();

        //startTomcat(applicationContext);暂时不用tomact容器 使用jetty
        WebServer webServer = getWebserver(applicationContext);
        webServer.start();
    }

    private static WebServer getWebserver(WebApplicationContext applicationContext) {
        // 依赖tomcat jetty undertow
        // key为beanName value为Bean对象
        //WebServer webServer = applicationContext.getBean(WebServer.class);
        //return webServer;
        Map<String, WebServer> webServers = applicationContext.getBeansOfType(WebServer.class);
        if(webServers.isEmpty()){
            throw new NullPointerException("啥bean都没配...");
        }
        if(webServers.size() > 1){
            throw new IllegalStateException("配置了多个bean");
        }
        // 返回唯一的一个
        return webServers.values().stream().findFirst().get();
    }

    /**
     *  内嵌tomcat
     * @param applicationContext
     */
//    public static void startTomcat(WebApplicationContext applicationContext){
//
//        Tomcat tomcat = new Tomcat();
//
//        Server server = tomcat.getServer();
//        Service service = server.findService("Tomcat");
//
//        Connector connector = new Connector();
//        connector.setPort(8081);
//
//        Engine engine = new StandardEngine();
//        engine.setDefaultHost("localhost");
//
//        Host host = new StandardHost();
//        host.setName("localhost");
//
//        String contextPath = "";
//        Context context = new StandardContext();
//        context.setPath(contextPath);
//        context.addLifecycleListener(new Tomcat.FixContextListener());
//
//        host.addChild(context);
//        engine.addChild(host);
//
//        service.setContainer(engine);
//        service.addConnector(connector);
//
//        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet(applicationContext));
//        context.addServletMappingDecoded("/*", "dispatcher");
//
//        try {
//            tomcat.start();
//        } catch (LifecycleException e) {
//            e.printStackTrace();
//        }

//    }
}
